﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using edowork.com.SQL2005;
using edowork.com.Model;

namespace WebInvoicingsys.system.baseset.sysrole
{
    public partial class rolegroup_add : System.Web.UI.Page
    {
        //前台输出提示信息变量
        public string alert_msg = "";

        #region 处理节点

        private void ProcSelectMenu(TreeNode tnNode, ref DataTable dtMunulist)
        {
            if (tnNode.Target.ToString() == "ROOT")
            {
                if (tnNode.ChildNodes.Count != 0)
                    for (int i = 0; i < tnNode.ChildNodes.Count; i++)
                        ProcSelectMenu(tnNode.ChildNodes[i], ref dtMunulist);
            }
            else
            {
                DataRow _dr = dtMunulist.NewRow();

                string[] _split = tnNode.Target.ToString().Split(",".ToCharArray());

                _dr["menuid"] = _split[0].ToString();
                _dr["parentid"] = _split[1].ToString();
                _dr["menuremark"] = _split[2].ToString();
                _dr["url"] = _split[3].ToString();

                if (tnNode.Checked)
                {
                    _dr["stu"] = "1";
                }
                else
                {
                    _dr["stu"] = "0";
                }

                dtMunulist.Rows.Add(_dr);

                if (tnNode.ChildNodes.Count != 0)
                    for (int i = 0; i < tnNode.ChildNodes.Count; i++)
                        ProcSelectMenu(tnNode.ChildNodes[i], ref dtMunulist);
            }
        }

        private void SetNode(TreeNode tn, bool bCheckStatus)
        {
            tn.Checked = bCheckStatus;

            if (tn.ChildNodes.Count != 0)
                for (int i = 0; i < tn.ChildNodes.Count; i++)
                {
                    TreeNode _tn = tn.ChildNodes[i];
                    SetNode(_tn, bCheckStatus);
                }
        }

        #endregion

        #region 构建菜单树

        private void GetMenuTree(DataSet dsMenu, string parentID, TreeNode pNode)
        {
            if ((dsMenu == null) || (dsMenu.Tables.Count <= 0))
            {
                return;
            }

            foreach (DataRow _dr in dsMenu.Tables[0].Rows)
            {
                if (_dr["parentid"].ToString().Trim() == parentID)
                {
                    string _split = "{0},{1},{2},{3}";

                    _split = String.Format(_split, _dr["menuid"].ToString(), _dr["parentid"].ToString(),
                                                   _dr["menuremark"].ToString(), _dr["url"].ToString());


                    TreeNode _treeNode = new TreeNode(_dr["menuremark"].ToString(), _dr["menuid"].ToString());
                    _treeNode.Target = _split;

                    DataRow[] drCH = dsMenu.Tables[0].Select(String.Format("parentid='{0}'", _dr["menuid"].ToString().Trim()));

                    if (drCH.Length > 0)
                    {
                        GetMenuTree(dsMenu, _dr["menuid"].ToString().Trim(), _treeNode);
                    }

                    _treeNode.Collapse();
                    pNode.ChildNodes.Add(_treeNode);
                }
            }
        }

        private void LoadMenuList()
        {
            Execute exec = new Execute(Session["connectionString"].ToString());

            string sql = "", error_msg = "";

            sql = "select * from menus";

            DataSet dsMenu = exec.ExecSQLQueryDataSet(sql, ref error_msg);

            if (dsMenu == null)
            {
                alert_msg = String.Format(Scripts.alert_warning, error_msg);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);
                return;
            }

            tvMenu.Nodes.Clear();

            TreeNode _treenode = new TreeNode();

            _treenode.Target = "ROOT";
            _treenode.Text = "系统功能";

            GetMenuTree(dsMenu, "0", _treenode);

            tvMenu.Nodes.Add(_treenode);

            _treenode.Expand();
        }

        #endregion

        protected void tvMenu_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {
            TreeNode _tn = e.Node;

            for (int i = 0; i < _tn.ChildNodes.Count; i++)
            {
                TreeNode _ctn = _tn.ChildNodes[i];
                SetNode(_ctn, _tn.Checked);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //载入功能菜单项
                LoadMenuList();

                /*
                 * 
                 * 尽管 TreeNodeCheckChanged 事件在回发时激发，但更改复选框不会导致回发。
                 * 而我们要求在选上一个节点的复选框之后同时选上所有子孙节点，所以希望提交服务器处理选上所有改节点的子孙节点，
                 * 然而现有的TreeNodeCheckChanged 事件不能满足要求，所以希望在复选框状态改变时候，强制提交服务器。
                 * 这里我们可以用js代码实现，代码如下所示： 
                 * 
                 * */
                tvMenu.Attributes.Add("onclick", "goPostBack()");
            }
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            alert_msg = "";

            edowork.com.Model.rulegroupInfo rulegroupInfo = new rulegroupInfo();
            edowork.com.Model.rulemenuInfo rulemenuInfo = new rulemenuInfo();

            rulegroupInfo.Rulegroupremark =  txt_rulegroupremark.Text.Trim();
            rulegroupInfo.Sysdate = DateTime.Now.ToString("yyyy-MM-dd");

            rulegroupInfo.Stu1 = cbstu1.Checked ? "1" : "0";

            if (String.IsNullOrEmpty(rulegroupInfo.Rulegroupremark))
            {
                alert_msg = String.Format(Scripts.alert_warning, "请输入权限组描述");

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                txt_rulegroupremark.Focus();

                return;
            }

            DataTable dtMenu = new DataTable();
            dtMenu.Columns.Add("menuid");
            dtMenu.Columns.Add("parentid");
            dtMenu.Columns.Add("menuremark");
            dtMenu.Columns.Add("url");
            dtMenu.Columns.Add("stu");

            //取得选择的菜单项
            TreeNode _tn = tvMenu.Nodes[0];

            ProcSelectMenu(_tn, ref dtMenu);

            //取得权限组编码
            rulegroupInfo.Rulegroupid = SysID.SCR_RoleID(Session["connectionString"].ToString(), ref alert_msg);

            if (String.IsNullOrEmpty(rulegroupInfo.Rulegroupid))
            {
                alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                return;
            }

            //保存数据入数据库
            using (edowork.com.SQL2005.TranUtil tranutil = new TranUtil(Session["connectionString"].ToString()))
            {
                System.Data.SqlClient.SqlTransaction tran = null;

                try
                {
                    tran = tranutil.GetSqlTransaction();
                }
                catch(Exception er)
                {
                    alert_msg = String.Format(Scripts.alert_warning, er.Message);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                edowork.com.SQL2005.Execute exec = new Execute(Session["connectionString"].ToString());

                string sql = "";
                int result = -1;

                //保存入rulegroup表
                sql = String.Format(rulegroupInfo.SQL_Insert(), rulegroupInfo.Rulegroupid, rulegroupInfo.Rulegroupremark, rulegroupInfo.Stu1, rulegroupInfo.Sysdate);

                result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                if (result <= 0)
                {
                    tran.Rollback();
                    tranutil.CloseConnection();

                    alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                    return;
                }

                //保存入rulemenu表
                rulemenuInfo.Rulegroupid = rulegroupInfo.Rulegroupid;
                rulemenuInfo.Sysdate = DateTime.Now.ToString("yyyy-MM-dd");

                foreach (DataRow dr in dtMenu.Rows)
                {
                    sql = String.Format(rulemenuInfo.SQL_Insert(), rulemenuInfo.Rulegroupid, dr["menuid"].ToString(), dr["stu"].ToString(), rulemenuInfo.Sysdate);

                    result = exec.ExecSQLQueryInt(sql, ref alert_msg, tran);

                    if (result <= 0)
                    {
                        tran.Rollback();
                        tranutil.CloseConnection();

                        alert_msg = String.Format(Scripts.alert_warning, alert_msg);

                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

                        return;
                    }
                }
                
                tran.Commit();
                tranutil.CloseConnection();
            }


            alert_msg = String.Format(Scripts.alert_success, Errormsg.success_Save);

            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", Scripts.alert_script, true);

             
        }

        //重置
        protected void btnReset_Click(object sender, EventArgs e)
        {
            txt_rulegroupremark.Text = "";
            cbstu1.Checked = true;
        }

        //返回
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("/system/baseset/sysrole/rolegroup.aspx");
        }
    }
}